<script setup lang='ts'>
import type { VxeGridInstance, VxeGridListeners, VxeGridProps } from 'vxe-table'

import { MemberDetail, MemberLevelInfo, MemberPage, MemberTagPage, MemberUpdatePoint, exportMember } from '@fl/api/anjutong'
import { ElCard } from 'element-plus'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import type { IRowV0 } from './list'

import { TimeLimit, formType, searchColumns } from './list'
import EditForm from './member-public/edit-form.vue'
import EditTag from './member-public/edit-tag.vue'
import GradeDetail from './member-public/grade-detail.vue'

const memberId = ref()
const router = useRouter()
const TitleEunm = {
    editPoint: '修改积分',
    editTag: '编辑标签',
    memberDetail: '会员详情',
} as const

const dialogTitle = ref()

const centerDialogVisible = ref(false)

const searchForm = ref({
    memberLevelList: [],
    memberTagIdList: [],
    memberType: '',
    mobile: '',
    nickName: '',
    realName: '',
    realNameAuthentication: '',
    timeLimit: null,
    idCardNo: '',
})
const editIntegralFrom = ref(
    {
        accumulatedPoints: '',
        memberId: 0,
        operationPoints: 0,
        remark: '',
    },
)

const xGrid = ref<VxeGridInstance<IRowV0>>()

const gridOptions = reactive<VxeGridProps<IRowV0>>({
    border: true,
    columnConfig: {
        resizable: true,
    },
    columns: [
        { field: 'realName', title: '会员姓名' },
        { field: 'nickName', title: '昵称' },
        { field: 'mobile', title: '手机号' },
        { field: 'gender', title: '性别' },
        { field: 'memberLevel', title: '会员等级' },
        { field: 'memberTagList', slots: { default: 'tag_default' }, title: '会员标签', width: 250 },
        { field: 'memberType', title: '用户类型' },
        { field: 'isAuthorizedPhone', slots: { default: 'isAuthorizedPhone' }, title: '授权手机号', width: 120, align: 'center' },
        { slots: { default: 'operate' }, title: '操作', width: 300 },
    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 530,
    keepSource: true,
    loading: false,
    pagerConfig: {
        currentPage: 1,
        enabled: true,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100, 200, 500],
        total: 0,
    },
    showOverflow: true,
})
const gridEvents: VxeGridListeners<IRowV0> = {
    pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
            gridOptions.pagerConfig.currentPage = currentPage
            gridOptions.pagerConfig.pageSize = pageSize
        }
        findList()
    },
}
findList()
function formatTime() {
    if (searchForm.value.timeLimit)
        return TimeLimit[searchForm.value.timeLimit]

    return ['', '']
}
async function findList() {
    gridOptions.loading = true
    const options = {
        objQuery: {
            endDateTime: formatTime()[1],
            memberLevelList: searchForm.value.memberLevelList,
            memberTagIdList: searchForm.value.memberTagIdList,
            memberType: searchForm.value.memberType,
            mobile: searchForm.value.mobile,
            nickName: searchForm.value.nickName,
            realName: searchForm.value.realName,
            realNameAuthentication: searchForm.value.realNameAuthentication,
            startDateTime: formatTime()[0],
            idCardNo: searchForm.value.idCardNo,
            isAuthorizedPhone: searchForm.value.isAuthorizedPhone == 0 ? '0' : searchForm.value.isAuthorizedPhone,
        },
        page: gridOptions.pagerConfig?.currentPage,
        size: gridOptions.pagerConfig?.pageSize,
    }
    const data = await MemberPage(options)
    gridOptions.loading = false
    if (gridOptions.pagerConfig)
        gridOptions.pagerConfig.total = data?.total ?? 0
    gridOptions.data = data?.records ?? []
}

function handleReset() {
    searchForm.value = {
        memberLevelList: [],
        memberTagIdList: [],
        memberType: '',
        mobile: '',
        nickName: '',
        realName: '',
        realNameAuthentication: '',
        timeLimit: null,
        idCardNo: '',
    }
    findList()
}

async function handleExport() {
    gridOptions.loading = true
    const params = {
        objQuery: {
            endDateTime: formatTime()[1],
            memberLevelList: searchForm.value.memberLevelList,
            memberTagIdList: searchForm.value.memberTagIdList,
            memberType: searchForm.value.memberType,
            mobile: searchForm.value.mobile,
            nickName: searchForm.value.nickName,
            realName: searchForm.value.realName,
            realNameAuthentication: searchForm.value.realNameAuthentication,
            startDateTime: formatTime()[0],
            idCardNo: searchForm.value.idCardNo,
            isAuthorizedPhone: searchForm.value.isAuthorizedPhone == 0 ? '0' : searchForm.value.isAuthorizedPhone,
        },
        page: gridOptions.pagerConfig?.currentPage,
        size: gridOptions.pagerConfig?.pageSize,
    }
    const result = await exportMember(params)
    const fileName = `会员查询${dayjs().format('YYYYMMDD')}`
    const blob = new Blob([result], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const href = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.style.display = 'none'
    a.href = href // 指定下载链接
    a.download = fileName // 指定下载文件名
    a.click()
    URL.revokeObjectURL(a.href) // 释放URL对象
    gridOptions.loading = false
}

const gradedetail = ref()
const tableData = ref({})

async function getMemberTagPage(getData?: any) {
    console.log(getData, 'getDatagetDatagetData')
    const options = {
        mainCat: '',
        page: getData.page,
        size: getData.size,
        sort: '',
        status: 1,
        subCat: '',
        tagName: getData.nameTap ? getData.nameTap : '',
        type: getData.typeTag,
    }
    console.log(options, 'optionsoptionsoptionsoptions')
    const data = await MemberTagPage(options)
    tableData.value = data
    console.log(tableData.value, 'MemberTagPageMemberTagPage搜索')
}

async function showDialog(row: any, title: string) {
    if (title === TitleEunm.editPoint)
        await getMemberDetail(row)
    if (title === TitleEunm.memberDetail)
        await getMemberLevelInfo(row)
    if (title === TitleEunm.editTag) {
        memberId.value = row.memberMetaId
        console.log('🚀 ~ showDialog ~ memberId:', row)
    }

    getMemberTagPage({})
    centerDialogVisible.value = true
    dialogTitle.value = title
}

async function getMemberDetail(row: any) {
    const data = await MemberDetail(row?.memberMetaId)
    editIntegralFrom.value.accumulatedPoints = data?.memberAssetsVO?.accumulatedPoints ?? 0
    editIntegralFrom.value.memberId = row?.memberMetaId ?? 0
}
async function getMemberLevelInfo(row: any) {
    const data = await MemberLevelInfo(row?.memberMetaId)
    gradedetail.value = data
}

function formatTag(row: any) {
    if (row?.memberTagList && row?.memberTagList?.length)
        return row?.memberTagList

    return []
}
const submitLoding = ref(false)
async function updatePoint() {
    submitLoding.value = true
    try {
        const option = {
            memberId: editIntegralFrom.value.memberId,
            operationPoints: editIntegralFrom.value.operationPoints,
            remark: editIntegralFrom.value.remark,
        }
        const data = await MemberUpdatePoint(option)
        if (data)
            ElMessage.success('修改成功')
        submitLoding.value = false
        centerDialogVisible.value = false
    }
    catch (error: any) {
        submitLoding.value = false
    }
}
function showDetail(row: any) {
    router.push(`/member-center/member/detail-record?id=${row.memberMetaId}`)
}
function search() {
    if (gridOptions.pagerConfig)
        gridOptions.pagerConfig.currentPage = 1
    findList()
}
function editTagSubmit() {
    centerDialogVisible.value = false
    findList()
}
</script>

<template>
    <ElCard class="mb-20">
        <PlusForm v-model="searchForm"
                  :row-props="{ gutter: 20 }"
                  :columns="searchColumns"
        >
            <template #footer>
                <div class="ml-auto">
                    <el-button type="primary"
                               @click="search"
                    >
                        查询
                    </el-button>

                    <el-button @click="handleReset">
                        重置
                    </el-button>

                    <el-button type="primary"
                               @click="handleExport"
                    >
                        导出
                    </el-button>
                </div>
            </template>
        </PlusForm>
    </ElCard>

    <ElCard>
        <div class="text-16 fw-700">
            会员列表
        </div>

        <vxe-grid ref="xGrid"
                  v-bind="gridOptions"
                  v-on="gridEvents"
        >
            <template #tag_default="{ row }">
                <!-- <span>{{ formatTag(row) }}</span> -->

                <span v-for="item in formatTag(row)"
                      :key="item.id"
                      class="px-10 py-5 mr-10 bg-#f2f2f2 border rounded-20"
                      style="display: inline-block;"
                >
                    {{ item.name }}
                </span>
            </template>

            <template #isAuthorizedPhone="{ row }">
                <span v-if="row.isAuthorizedPhone === 1">是</span>

                <span v-if="row.isAuthorizedPhone === 0">否</span>
            </template>

            <template #operate="{ row }">
                <vxe-button size="mini"
                            :content="TitleEunm.memberDetail"
                            @click="showDetail(row)"
                />

                <vxe-button size="mini"
                            :content="TitleEunm.editPoint"
                            @click="showDialog(row, TitleEunm.editPoint)"
                />

                <vxe-button size="mini"
                            :content="TitleEunm.editTag"
                            @click="showDialog(row, TitleEunm.editTag)"
                />
            </template>
        </vxe-grid>
    </ElCard>

    <el-dialog v-model="centerDialogVisible"
               width="80%"
               :title="dialogTitle"
               destroy-on-close
    >
        <template v-if="dialogTitle === TitleEunm.memberDetail">
            <GradeDetail :gradedetail="gradedetail"
                         @close="centerDialogVisible = false"
            />
        </template>

        <template v-if="dialogTitle === TitleEunm.editPoint">
            <EditForm :type="formType.integral"
                      :editfrom="editIntegralFrom"
                      :loading="submitLoding"
                      @close="centerDialogVisible = false"
                      @submit="updatePoint"
            />
        </template>

        <template v-if="dialogTitle === TitleEunm.editTag">
            <EditTag :id="memberId"
                     @close="centerDialogVisible = false"
                     @submit="editTagSubmit"
            />
        </template>
    </el-dialog>
</template>
